package com.davinci.freemarket.businessLayer.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.davinci.freemarket.businessLayer.controllers.RegisterController;
import com.davinci.freemarket.businessLayer.utils.WebParamsStandarized;
import com.davinci.freemarket.dataAccessLayer.accessdata.user.UserDAO;
import com.davinci.freemarket.dataModelLayer.model.UserModel;

public class RegisterServlet extends HttpServlet{

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		/**
		 *la tabla USUARIO
		 * 
		 * @param nick
		 * @param pass
		 * @param email
		 * @param address
		 * @param name
		 * @param lastname
		 * @param phone
		 * @return
		 */
		
		String nick = request.getParameter("nick");
		String password = request.getParameter("password");
		String email = request.getParameter("email");
		String address = request.getParameter("address");
		String name = request.getParameter("name");
		String lastname = request.getParameter("lastname");
		String phone = request.getParameter("phone");
		
		UserModel userModel = new UserModel();

		userModel.setNick(nick);
		userModel.setPass(password);
		userModel.setEmail(email);
		userModel.setAddress(address);
		userModel.setName(name);
		userModel.setLastname(lastname);
		userModel.setPhone(phone);
		
		RegisterController  registerController = new RegisterController();
		boolean userRegisterOk = registerController.addUser(userModel);
		if(userRegisterOk){
			UserModel user = new UserModel();
			user.setEmail(request.getParameter(WebParamsStandarized.PARAMETER_LOGIN_MAIL));
			user.setPass(request.getParameter(WebParamsStandarized.PARAMETER_LOGIN_PASSWORD));
			UserDAO userDAO = new UserDAO();
			try {
				user = userDAO.login(user);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			if (user.isUserValid()) {
				HttpSession session = request.getSession(true);
				session.setAttribute("currentSessionUser",user);
				response.sendRedirect("../index.jsp");
			} else {
				response.sendRedirect("../index.jsp?error=Registro Incorrecto");
			}
		}else{
			PrintWriter pw = response.getWriter();
					pw.println("Register Fail");
		}
	}
}
